﻿// Type: D2L.Extensibility.AuthSdk.Restsharp.ValenceAuthenticator
// Assembly: D2L.Extensibility.AuthSdk.Restsharp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: CB900437-6C64-4664-90CE-6FCF112716A7
// Assembly location: C:\Users\leandro.perdizo\Desktop\D2L.Extensibility.AuthSdk.Restsharp.dll

using D2L.Extensibility.AuthSdk;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using RestSharp;

namespace D2L.Extensibility.AuthSdk.Restsharp
{
  public sealed class ValenceAuthenticator : IAuthenticator
  {
    private readonly ID2LUserContext m_context;

    public ValenceAuthenticator(ID2LUserContext context)
    {
      this.m_context = context;
    }

    private string AdaptMethod(Method m)
    {
      switch ((int) m)
      {
        case 0:
          return "GET";
        case 1:
          return "POST";
        case 2:
          return "PUT";
        case 3:
          return "DELETE";
        default:
          throw new ArgumentException("Unhandled method: " + (object) m);
      }
    }

    private string CreateAuthQueryString(IEnumerable<Tuple<string, string>> tokens)
    {
      return string.Join("&", Enumerable.Select<Tuple<string, string>, string>(tokens, (Func<Tuple<string, string>, string>) (token => string.Format("{0}={1}", (object) token.Item1, (object) token.Item2))));
    }

    public void Authenticate(IRestClient client, IRestRequest request)
    {
      Uri uri = client.BuildUri(request);
      string str1 = this.AdaptMethod(request.get_Method());
      this.m_context.CreateAuthenticatedUri(uri, str1);
      this.m_context.CreateAuthenticatedUri(uri.AbsolutePath, str1);
      string authQueryString = this.CreateAuthQueryString(this.m_context.CreateAuthenticatedTokens(uri, str1));
      if (uri.ToString().IndexOf('?') != -1)
      {
        string pathAndQuery = uri.PathAndQuery;
        int startIndex = pathAndQuery.IndexOf(request.get_Resource(), StringComparison.Ordinal);
        request.set_Resource(pathAndQuery.Substring(startIndex, pathAndQuery.Length - startIndex));
        IRestRequest irestRequest = request;
        string str2 = irestRequest.get_Resource() + "&" + authQueryString;
        irestRequest.set_Resource(str2);
        request.get_Parameters().Clear();
      }
      else
      {
        IRestRequest irestRequest = request;
        string str2 = irestRequest.get_Resource() + "?" + authQueryString;
        irestRequest.set_Resource(str2);
      }
    }
  }
}
